<?php
namespace app\controller\app;

use app\BaseController;
use app\model\CraneCar;
use app\model\Elevator;
use app\model\ElevatorAlarmNdata;
use app\model\ElevatorAlarmRdata;
use app\model\ElevatorNdata;
use app\model\ElevatorRdata;
use app\model\Project;
use app\model\TowerAlarmNdata;
use app\model\TowerAlarmRdata;
use app\model\TowerAnticollision;
use app\model\TowerCar;
use app\model\TowerCrane;
use app\model\TowerCraneNdata;
use app\model\TowerCraneRdata;
use think\facade\Db;
use think\Request;

//use GuzzleHttp\Client;

//
class EquipmentController extends BaseController
{

    //设备绑定
    public function addEquipment(Request $request)
    {
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        //查询设备
        $equipment = $equipmentModel::where('eid', $request->param('eid'))->find();
        if (!$equipment) {
            return fail(null, '不存在设备');
        }
        $old_pid = $equipment->pid; //设备老PID
        $data = $request->post();
        if($old_pid){
            if($old_pid != $request->param('pid')){
                return fail(null, '请先解绑项目');
            }
        }
        //判断验证码
        if ($data['vcode'] != $equipment->vcode) {
            return fail(null, '验证码错误');
        }
        //校验设备归属--盘石,安徽
        if ($data['special_customization'] != $equipment->special_customization) {
            return fail(null, '设备归属异常');
        }
        foreach ($data as $key => $value) {
            $equipment->$key = $value;
        }
        $equipment->bind_status = 1; //设备绑定
        $equipment->bind_time = date('Y-m-d H:i:s', time()); //设备绑定
        $rq = $equipment->save();

        //项目-设备数量增加
        if ($old_pid != $request->param('pid') && $rq = 1) {
            $Project = Project::find($request->param('pid'));
            $equipment->pname = $Project->pname; //更新设备项目名称
            $rq = $equipment->save();
            switch ($data['model']) {
                case 'D101':
                    $Project->d101_num += 1;
                    break;
                case 'T102':
                    $Project->t102_num += 1;
                    break;
                case 'T104':
                    $Project->t104_num += 1;
                    break;
                case 'T105':
                    $Project->t105_num += 1;
                    break;
                case 'T107-A2':
                    $Project->t107_a2_num += 1;
                    break;
                case 'T107-A2X':
                    $Project->t107_a2x_num += 1;
                    break;
                case 'S103':
                    $Project->s103_num += 1;
                    break;
                default:
                    break;
            }
            $rq = $Project->save();
        }

        if ($rq) {
            return success($equipment);
        }
    }
    //设备解除绑定
    public function relieveBind(Request $request)
    {
        /*
        清除项目设备数量
        清除我的统计
         */
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        //查询设备
        $equipment = $equipmentModel::where('eid', $request->param('eid'))->find();
        //查询项目
        $Project = Project::find($equipment->pid);
        if ($Project) {
            switch ($equipment->model) {
                case 'D101':
                    $Project->d101_num -= 1;
                    break;
                case 'T102':
                    $Project->t102_num -= 1;
                    break;
                case 'T104':
                    $Project->t104_num -= 1;
                    break;
                case 'T105':
                    $Project->t105_num -= 1;
                    break;
                case 'T107-A2':
                    $Project->t107_a2_num -= 1;
                    break;
                case 'T107-A2X':
                    $Project->t107_a2x_num -= 1;
                    break;
                case 'S103':
                    $Project->s103_num -= 1;
                    break;
                default:
                    break;
            }
            $rq = $Project->save();
        }
        $equipment->pid = 0;
        $equipment->relieve_time = date('Y-m-d H:i:s', time()); //解绑时间
        $equipment->install_status = 0;
        $equipment->bind_status = 0;
        $equipment->bind_time = null;
        $equipment->install_time = null;
        $equipment->belong_user = null;
        $equipment->pname = null;

        $rq = $equipment->save();
        if ($rq) {
            return success(null, '解除绑定');
        }
    }
    // 设备列表
    public function equipmentList(Request $request)
    {
        $where = [];
        if ($request->has('username')) {
            $username = $request->param('username');
            $where[] = ['belong_user', 'find in set', $request->param('username')];
        }
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        $dataType = ['TowerCrane', 'Elevator', 'TowerCar', 'CraneCar'];
        if (!in_array($equipmentType, $dataType)) {
            return success([]);
        }
        $EquipmentList = $equipmentModel::where($where)->order('bind_time', 'desc')->field('pname,model,eid,ename,sim,online,bind_time,signal_level')->select();
        foreach ($EquipmentList as $key => $value) { //安卓设备在线离线
            if ($value->model == 'T107-A2X' || $value->model == 'T107-A2') {
                if ($value->online = 1) {
                    $update_time = strtotime(TowerCraneNdata::where('eid', $value->eid)->value('update_time'));
                    if (time() - $update_time > 120) {
                        $value->online = 0;
                        TowerCrane::where('eid', $value->eid)->update(['online' => 0]);
                    }
                }
            }
        }
        return success($EquipmentList);
    }
    // 塔机设备详情
    public function equipmentData(Request $request)
    {
        if ($request->has('webkey')) {
            $data = $request->param('webkey');
            $mb_convert_encoding = mb_convert_encoding($request->param('webkey'), 'utf-8');
            $data = str_replace(" ", "+", $data); //替换url中的+号
            $method = 'aes-128-cbc';
            $key = '782466a7dada1345';
            $decrypt = openssl_decrypt($data, $method, $key, 0, $key);
        }
        $log = $request->param();
        //创建model
        $equipmentType = $request->param('equipmentType');
        if ($equipmentType == 'TowerCrane') {
            if (isset($decrypt)) {
                $eid = $decrypt;
            } else {
                $eid = $request->param('eid');
            }
            $list['info'] = TowerCrane::where('eid', $eid)->field('pname,eid,ename,model,max_height,tower_arm,tower_rate,communcation_address,communcation_group,driver_tel,signal_level')->find();
            $list['ndata'] = TowerCraneNdata::where('eid', $eid)->find();
            $list['alarm'] = TowerAlarmNdata::where('eid', $eid)->find();
            //round($param['height'], 2);
            if ($list['ndata']) {
                $list['info']->max_height > 0? $list['info']->max_height : $list['info']->max_height = 50;
                $list['ndata']->height_percent = round($list['ndata']->height, 2) * 100 / $list['info']->max_height;
                $list['ndata']->height_percent > 100 ? $list['ndata']->height_percent = 100 : $list['ndata']->height_percent;
            }
            if($list['alarm']){
                if (!$list['ndata']) {
                    $list['ndata'] = null;
                }else{
                    $list['ndata']->arm_percent = round($list['ndata']->amplitude, 2) * 100 / $list['info']->tower_arm;
                    $list['ndata']->arm_percent > 100 ? $list['ndata']->arm_percent = 100 : $list['ndata']->arm_percent;
                }
            }

        } elseif ($equipmentType == 'Elevator') {
            if (isset($decrypt)) {
                $eid = $decrypt;
            } else {
                $eid = $request->param('eid');
            }
            $list['info'] = Elevator::where('eid', $eid)->find();
            $list['ndata'] = ElevatorNdata::where('eid', $eid)->find();
            $list['alarm'] = ElevatorAlarmNdata::where('eid', $eid)->find();
        } elseif ($equipmentType == 'TowerCar') {
            if (isset($decrypt)) {
                $eid = $decrypt;
            } else {
                $eid = $request->param('eid');
            }
            $list['info'] = TowerCar::where('eid', $eid)->find();
            $list['ndata'] = null;
            $list['alarm'] = null;
        }
        // Log::write($list, 'equipmentData');
        return success($list);
    }
    // 塔机设备配置
    public function equipmentConfigList(Request $request)
    {
        //创建model
        $equipmentType = $request->param('equipmentType');
        if ($equipmentType == 'TowerCrane') {
            $list = TowerCrane::where('eid', $request->param('eid'))->find();
            /* 补充信息 */
            // $list =TowerCrane::select();
            // foreach ($list as $key => $value) {
            //     if($value['sim']){
            //         $sim = substr($value['sim'], 0, -1);
            //         $access = DB::table('simcard')->where('iccid',$sim)->value('access');
            //         $re = Db::name('tower_crane')->where('eid', $value['eid'])->update(['access' => $access]);
            //     }
            // }
            // $list =TowerCrane::select();
            // foreach ($list as $key => $value) {
            //     $sim = DB::table('tower_crane_save')->where('eid',$value['eid'])->value('sim');
            //     $re = Db::name('tower_crane')->where('eid', $value['eid'])->update(['sim' => $sim]);
            // }

        } elseif ($equipmentType == 'Elevator') {
            $list = Elevator::where('eid', $request->param('eid'))->find();
        } elseif ($equipmentType == 'TowerCar') {
            $list = TowerCar::where('eid', $request->param('eid'))->find();
        } elseif ($equipmentType == 'CraneCar') {
            $list = CraneCar::where('eid', $request->param('eid'))->find();
        }
        return success($list);
    }
    // 塔机设备配置
    public function equipmentInfoByMac(Request $request)
    {
        //创建model
        $equipmentType = $request->param('equipmentType');
        if ($equipmentType == 'TowerCrane') {
            $list = TowerCrane::where('mac', $request->param('mac'))->find();
        } elseif ($equipmentType == 'Elevator') {
            $list = Elevator::where('mac', $request->param('mac'))->find();
        } elseif ($equipmentType == 'TowerCar') {
            $list = TowerCar::where('mac', $request->param('mac'))->find();
        } elseif ($equipmentType == 'CraneCar') {
            $list = CraneCar::where('mac', $request->param('mac'))->find();
        }
        return success($list);
    }
    // 报警TYPE查询
    public function alarmTypeList(Request $request)
    {
        //创建model
        $etype = $request->param('etype');
        $list = DB::table('alarm_type')->where('etype', $request->param('etype'))->field('alarm_type,content')->select();
        return success($list);
    }
    // 塔机防碰撞数据
    public function anticollisionData(Request $request)
    {
        //创建model
        // $eids = explode(",",$request->param('eid'));
        $list = TowerCraneNdata::where('eid', 'in', $request->param('eid'))->select();
        return success($list);
    }
    // 塔机防碰撞数据--设置参数
    public function updateAnticollisionData(Request $request)
    {
        $value = TowerAnticollision::where('main_id', $request->param('eid'))->find();
        $towerInfo = TowerCrane::where('eid', $request->param('eid'))->find();
        if ($value) {
            $anticollisionData['early_warning'] = $value->early_warning;
            $anticollisionData['alarm_value'] = $value->alarm_value;
            $anticollisionData['anticollision'][0]['id'] = $value->main_id;
            $anticollisionData['anticollision'][0]['name'] = $value->main_name;
            $anticollisionData['anticollision'][0]['arm_length'] = $value->main_arm_length;
            $anticollisionData['anticollision'][0]['max_height'] = $towerInfo->max_height;

            $slave_ids = explode(",", $value->slave_ids);
            $slave_names = explode(",", $value->slave_names);
            $slave_arm_lengths = explode(",", $value->slave_arm_lengths);
            $slave_distances = explode(",", $value->slave_distances);
            $slave_angles = explode(",", $value->slave_angles);
            $slave_height = explode(",", $value->slave_height);
            foreach ($slave_ids as $key => $value) {
                $slave['id'] = $slave_ids[$key];
                $slave['name'] = $slave_names[$key];
                $slave['arm_length'] = $slave_arm_lengths[$key];
                $slave['distance'] = $slave_distances[$key];
                $slave['angle'] = $slave_angles[$key];
                $slave['height'] = $slave_height[$key];
                array_push($anticollisionData['anticollision'], $slave);
            }
            return success($anticollisionData);
        } else {
            $anticollisionData['early_warning'] = 15;
            $anticollisionData['alarm_value'] = 10;
            $anticollisionData['anticollision'][0]['id'] = $towerInfo->eid;
            $anticollisionData['anticollision'][0]['name'] = $towerInfo->ename;
            $anticollisionData['anticollision'][0]['arm_length'] = $towerInfo->tower_arm;
            $anticollisionData['anticollision'][0]['max_height'] = $towerInfo->max_height;
            return success($anticollisionData);
        }
    }
    // 塔机空间限位数据--设置参数
    public function updateSpaceLimitData(Request $request)
    {
        $value = TowerAnticollision::where('main_id', $request->param('eid'))->find();
        if ($value) {
            $spaceLimitData['id'] = $value->main_id;
            $spaceLimitData['spaceLimit'] = [];
            $slave_ids = explode(",", $value->slave_ids);
            array_unshift($slave_ids, $value->main_id); //头部添加
            $height_start = explode(",", $value->height_start);
            $height_end = explode(",", $value->height_end);
            $amplitude_start = explode(",", $value->amplitude_start);
            $amplitude_end = explode(",", $value->amplitude_end);
            $angle_start = explode(",", $value->angle_start);
            $angle_end = explode(",", $value->angle_end);
            foreach ($height_start as $key => $value) {
                // $slave['id'] = (int) $slave_ids[$key];
                $slave['id'] = (int)$spaceLimitData['id'];
                $slave['height_start'] = $height_start[$key];
                $slave['height_end'] = $height_end[$key];
                $slave['amplitude_start'] = $amplitude_start[$key];
                $slave['amplitude_end'] = $amplitude_end[$key];
                $slave['angle_start'] = $angle_start[$key];
                $slave['angle_end'] = $angle_end[$key];
                array_push($spaceLimitData['spaceLimit'], $slave);
            }
            return success($spaceLimitData);
        } else {
            $spaceLimitData['id'] = $request->param('eid');
            return success($spaceLimitData);
        }
    }
    /* 设备报警数据 */
    public function equipmentAlarmList(Request $request)
    {
        $equipmentType = $request->param('equipmentType');

        $page = $request->param('pageSize');
        $post = $request->param();
        $where = [];
        if (isset($post['eid'])) {
            $where[] = ['eid', '=', $post['eid']];
        }
        switch ($equipmentType) {
            case 'TowerCrane':
                $list = TowerAlarmRdata::where($where)->order('id', 'desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
                break;
            case 'Elevator':
                $list = ElevatorAlarmRdata::where($where)->order('id', 'desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
                break;
            default:
                break;
        }
        return successPage($list);
    }
    /* 设备历史数据 */
    public function equipmentDataList(Request $request)
    {
        $equipmentType = $request->param('equipmentType');

        $page = $request->param('pageSize');
        $post = $request->param();
        $where = [];
        if (isset($post['eid'])) {
            $where[] = ['eid', '=', $post['eid']];
        }
        switch ($equipmentType) {
            case 'TowerCrane':
                $list = TowerCraneRdata::where($where)->order('id', 'desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
                break;
            case 'Elevator':
                $list = ElevatorRdata::where($where)->order('id', 'desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
                break;
            default:
                break;
        }

        return successPage($list);
    }
    /* 设备参数下发---传感器数据 */
    public function updateEquipmentSensor(Request $request)
    {
        //创建model
        $equipmentType = $request->param('equipmentType');
        $modelName = 'app\model\\' . $equipmentType;
        $equipmentModel = new $modelName;
        $equipment = $equipmentModel::where('eid', $request->param('eid'))->find();
        $data = $request->post();
        unset($data['equipmentType']);
        if ($equipment) {
            foreach ($data as $key => $value) {
                $equipment->$key = $value;
            }
        }
        $rq = $equipment->save();
        if ($rq) {
            return success($equipment);
        }
    }
}
